# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     pdfSplitWithRedis
|Author:        WYT
|date:          2020/6/11
 ----------------------------------------
|  Change Activity:
|                   2020/6/11:
-----------------------------------------
"""
import json
import os
import time

from base.BaseMethod import BM
from settings import materials_path, oss_id, oss_secret, oss_endpoint, web_type, log_path, base_path
from util.DataQuery.DbTools import DbTools
from util.Logger import Logger
from util.OSS import OSS
from util.pdfSplit import g
from util.inform.sendEmail import sendEmail
from util.pdfSplit.pdf_split import Split
from util.redis_manage_file import redisManageFile


def remove_dir(dir=""):
    if os.path.exists(dir):
        if not os.path.isdir(dir):
            os.remove(dir)
            return
        x = os.listdir(dir)
        for i in x:
            new_path = os.path.join(dir, i)
            if not os.path.isdir(new_path):
                os.remove(new_path)
                return remove_dir(os.path.dirname(new_path))
            else:
                remove_dir(new_path)
            # os.rmdir(new_path)
    os.rmdir(dir)


def get_pdf_and_split(res, webType=None):
    file_operate = None
    if type(res) == bytes:
        res = res.decode("utf-8")
    if isinstance(res, str):
        file_operate = json.loads(res)
    elif isinstance(res, dict):
        file_operate = res
    biz_code = file_operate.get("biz_code")
    co_id = file_operate.get("co_id")
    year = file_operate.get("year")
    file_path = file_operate.get("file_path")
    description = file_operate.get("description")
    operate = file_operate.get("operate")
    print("file_operate: {}".format(file_operate))
    if operate == "delete":
        # TODO 删除 file_path 中的所有文件和 file_path
        remove_dir(dir=file_path)
    else:
        # TODO 通过 取到的参数获取文件路径
        file_remote_path = DbTools.get_doc_path_by_info(co_id=co_id, biz_code=biz_code, description=description)
        g.logger.info("file_remote_path: {}".format(file_remote_path))
        if file_remote_path is None:
            return
        if not file_remote_path.get("doc_path"):
            return
        file_remote_path = file_remote_path.get("doc_path")

        bucket_name, file_name = file_remote_path.split("/")
        # TODO 使用文件路径获取文件到本地
        local_path = materials_path + "\\original_files"
        # TODO 暂时使用 加工过后的文件

        if not os.path.exists(local_path):
            os.mkdir(local_path)
        path = os.path.join(local_path, file_name)
        g.logger.info("file_path: {}".format(file_name))
        split = Split(pdf_way=path, pdf_save_way=file_path, co_id=co_id, year=year, web_type=web_type if not webType else webType)
        split.run()
        # split.join()
        # TODO 将拆分完成之后的 大文件整个删除
        # remove_dir(path)


# TODO 与材料上传同时启动
def split():
    g.logger = Logger(log_file_name=log_path.replace("log.txt", "autoflow_pdfSplit.log"), log_level=Logger.DEBUG,
                      logger_name="autoflow_pdfSplit").get_log()
    while True:
        res = None
        while True:
            try:
                res = redisManageFile().list_get(list_key=BM.get_host())
                if res is not None:
                    pass
            except redisManageFile.error as err:
                g.logger.error("连接redis错误: err: {}".format(err))
            else:
                break
        if res is not None:
            if isinstance(res, bytes):
                res = res.decode("utf-8")
            # if web_type in res:
            #     redisManageFile().list_put(list_key=BM.get_host(), list_value=res)
            # else:
            g.logger.info("redis value: {}".format(res))
            try:
                print("res is not None")
                get_pdf_and_split(res)
            except Exception as err:
                # TODO 发送邮件 通知pdf拆分错误
                sendEmail(subject="autoflow_split_pdf", content="拆分pdf错误： {} \n 错误信息： {}".format(res, err))

        else:
            time.sleep(5)


if __name__ == '__main__':
    # remove_dir("C:\\Users\\Administrator\\Desktop\\Project\\autoflow\materials\\省网")
    # split()

    g.logger = Logger(log_file_name=log_path.replace("log.txt", "autoflow_pdfSplit.log"), log_level=Logger.DEBUG,
                      logger_name="autoflow_pdfSplit").get_log()
    co_ids = [
        # 115601, 118493, 122031, 125344, 327633, 482692,
        # 116254, 513041, 513669,
        # 513687, 79421, 1004878,
        # 882075, 375534,
        # 114707,
        # 121773,
        # 516536, 882089, 93371, 991943, 999047,
        # 517774, 712476, 93303, 514880, 513640, 724852, 991943
        # 114707, 96128
        # 95757, 96128, 121293, 790043, 369937
        977703
    ]
    path = "\\\\MOURNER\\share\\materials"
    # path = "{}\\materials".format(base_path)
    for i in co_ids:
        get_pdf_and_split(res=json.dumps({"biz_code": "GR2021{}".format(i), "co_id": i, "year": 2021, "file_path": "{}\\GR_2021\\ctp\\GR_{}".format(path, i), "description": "0", "operate": "split"}))
    pass

    # 专利权人不一致
    flag = 4
    # 无效专利
    flag = 0
    # 佰腾未返回数据
    flag = 2
    # 接口响应异常
    flag = 3
